package com.xrit.sunnyday.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xrit.sunnyday.constant.MessageConstant;
import com.xrit.sunnyday.constant.RedisMessageConstant;
import com.xrit.sunnyday.entity.Result;
import com.xrit.sunnyday.pojo.Order;
import com.xrit.sunnyday.service.OrderService;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderMobileController {
    @Autowired
    private JedisPool jedisPool;

    @Reference
    private OrderService orderService;

    /**
     * 处理添加预约信息
     * 1.接受前端页面“立即预约”的ajax请求
     * 2.判断验证码是否填写正确-和redis存的值做对比，不正确直接return
     * 3.只有验证码正确的情况下才将预约信息传递到(Service+dao)模块
     */
    @PostMapping("/submit")
    public Result submit(@RequestBody Map<String,String> paraMap){
        //1.从reis连接池中获取连接
        Jedis jedis = jedisPool.getResource();
        //1.1.拿到用户传过来的手机号
        String telephone = paraMap.get("telephone");
        //1.2.组拼key
        String key = RedisMessageConstant.SENDTYPE_ORDER+"_"+telephone;
        //1.3根据key获取
        String codeInRedis = jedis.get(key);
        //1.4判断
        if (StringUtils.isEmpty(codeInRedis)){
            //1.5 null
            return new Result(false,"验证码失效，请重新发送!");
        }
        //2.有值，取出前端页面传过来的验证码
        String validateCode = paraMap.get("validateCode");
        if (!codeInRedis.equals(validateCode)){
            //2.1如果不一致
            return new Result(false,"验证码错误！");
        }
        //2.2 匹配一致，代表这次请求已经完成，删除redis的key
        //jedis.del(key); //学习阶段，不建议删除
        //补充传递的数据
        paraMap.put("orderType", Order.ORDERTYPE_WEIXIN);
        //3.数据都通过，传递给service层
        Order order = orderService.submitOrder(paraMap);
        return new Result(true, MessageConstant.ORDER_SUCCESS,order);
    }

    @GetMapping("/findById")
    public Result findById(int id){
        //多表联查
        Map<String,Object> orderInfo = orderService.findById4Detail(id);
        return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS,orderInfo);
    }
}
